package com.example.servicelogin.services.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisServiceImpl {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public <T> T getObject(String key, Class<T> clazz) {
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {
            return null;
        }
        return clazz.cast(obj);
    }
    public void set(String key, Object value, long expireTime) {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = null;
        try {
            jsonString = objectMapper.writeValueAsString(value);
            System.out.println(jsonString);
        } catch (Exception e) {
            e.printStackTrace();    
        }
        redisTemplate.opsForValue().set(key, jsonString.toString(), expireTime, TimeUnit.SECONDS);
    }
    public <T> T get(String key, Class<T> valueType) {
        ObjectMapper objectMapper = new ObjectMapper();
        T jsonString = null;
        try {
            Object o = redisTemplate.opsForValue().get(key);
            if (o == null) {
                System.out.println("key不存在");
                return null;
            }
            jsonString = objectMapper.readValue(redisTemplate.opsForValue().get(key).toString(), valueType);
            System.out.println(jsonString);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return jsonString;
    }

    public void del(String key) {
        redisTemplate.delete(key);
    }
}
